FROM golang:1.21 AS builder

WORKDIR /app
COPY . .

ARG GITHUB_SHA
ARG GITHUB_REF_NAME
ARG TARGETS="linux-amd64"
ARG STATIC_TARGETS="linux-amd64"

RUN set -eux && \
    go get github.com/robfig/cron && \
    BUILD=${GITHUB_SHA:+${GITHUB_SHA:0:7}} && \
    BUILD=${BUILD:-$(git rev-parse --short HEAD)} && \
    VERSION=${GITHUB_REF_NAME:-$(git describe --tags)} && \
    mkdir -p dist && \
    for TARGET in $TARGETS; do \
        GOOS=${TARGET%-*} GOARCH=${TARGET#*-} go build -o dist/go-cron-$TARGET \
        -ldflags "-X main.build=$BUILD -X main.version=$VERSION" main.go; \
    done && \
    for TARGET in $STATIC_TARGETS; do \
        CGO_ENABLED=0 GOOS=${TARGET%-*} GOARCH=${TARGET#*-} go build -o dist/go-cron-$TARGET-static \
        -ldflags "-X main.build=$BUILD -X main.version=$VERSION -extldflags -static" main.go; \
    done

FROM alpine:3.21 AS runtime
COPY --from=builder /app/dist/go-cron-linux-amd64-static /usr/local/bin/go-cron 

RUN set -x \
	&& apk update && apk add ca-certificates curl tzdata rsync \
        && chmod a+x /usr/local/bin/go-cron \
        && mkdir /share

ENV SCHEDULE="@daily" \
    HEALTHCHECK_PORT=8080 \
    TZ=Asia/Shanghai

COPY entrypoint.sh /entrypoint.sh
COPY run.sh /run.sh

ENTRYPOINT ["/entrypoint.sh"]
CMD ["/run.sh"]

HEALTHCHECK --interval=5m --timeout=3s \
  CMD curl -f "http://localhost:$HEALTHCHECK_PORT/" || exit 1
